//
//  lnddNetworkManager.swift
//  maiguadan
//
//  Created by 邵禹曦 on 2019/11/13.
//  Copyright © 2019 白雨桐. All rights reserved.
//

import UIKit
import AFNetworking

///swift 的枚举啊支持任意数据类型
/// swift / enum 在 OC中都只是支持整数
enum HTTPMethod {
    case GET
    case POST
}

/// 网络管理工具
class lnddNetworkManager: AFHTTPSessionManager {
    
    /// 单例模式 - 静态区 / 常量 /  闭包 /  在第一次访问时，l执行闭包，并且将结果保存在shared常量中
    static let shared = lnddNetworkManager()
    
    /// 使用一个函数封装 AFN 的 GET / POST 请求
    func request(method: HTTPMethod = .GET, URLString: String, parameters: [String:Any], completion: @escaping(_ json: Any?, _ isSuccess: Bool)->()) {
        
        /// 闭包
        let success = { (task: URLSessionDataTask, json: Any?)->() in
            completion(json, true)
        }
        let failure = { (task: URLSessionDataTask?, error: Error)->() in
            print("网络请求失败 \(error)")
            completion(nil, false)
        }
        
        if method == .GET {
            get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        } else {
            /// error 通常比较吓人
            
            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
        
        
    }
    
    func _curlGet(url:String)
    {
        
        let url = URL(string: url)
        let task = URLSession.shared.dataTask(with: url! as URL) { data, response, error in
            guard let data = data, error == nil else {
                print("网络请求失败");
                return
                
            }
            print(NSString(data: data, encoding: String.Encoding.utf8.rawValue)!)
            
            
        }
        
        
        task.resume()
    }

}
